package com.easemob.helpdesk.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.easemob.helpdesk.utils.Base64Utils;
import com.easemob.helpdesk.utils.FileUtils;
import com.housekeeperapp.R;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;


import kr.co.namee.permissiongen.PermissionGen;

/**
 * Created by xiaolong.wei on 2019/5/24.
 */

public class IDCardVerifyStepTwoActivity extends BaseActivityV2 implements  View.OnClickListener{
    private static final int REQUEST_TAKE_PHOTO_CODE = 1001;
    private static final int REQUEST_CODE_REQUEST_PERMISSIONS = 2001;
    private static final int REQUEST_CODE_ALERT_DIALOG_ACCESS = 3001;

    private static final String TAG = "IDCardVerStepTwoAct";
    @Override
    public void onClick(View view) {
        if(view.getId()== R.id.back){
            finish();
        }else if(view.getId()==R.id.id_card_front_image){

        }
        else if(view.getId()==R.id.clear_front_image){
            clearImage("front");
        }    else if(view.getId()==R.id.id_card_front_place_holder_layout){
            mCurrentType = "front";
            checkPermission();
        }
        else if(view.getId()==R.id.clear_back_image){
            clearImage("back");
        }
        else if(view.getId()==R.id.id_card_back_place_holder_layout){
            mCurrentType = "back";
            checkPermission();
        }
        else if(view.getId()==R.id.submit){
            if (System.currentTimeMillis() - mClickTime < 1000){//防止双击
                return;
            }
            submit();
            mClickTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void initFindView() {
        mIdCardFrontImage=findViewById(R.id.id_card_front_image);

        mClearFrontImage=findViewById(R.id.clear_front_image);
        mClearFrontImage.setOnClickListener(this);
        mIdCardFrontPlaceHolderLayout=findViewById(R.id.id_card_front_place_holder_layout);
        mIdCardFrontPlaceHolderLayout.setOnClickListener(this);

        mIdCardFrontLayout=findViewById(R.id.id_card_front_layout);

        mIdCardBackImage=findViewById(R.id.id_card_back_image);

        mClearBackImage=findViewById(R.id.clear_back_image);
        mClearBackImage.setOnClickListener(this);

        mIdCardBackPlaceHolderLayout=findViewById(R.id.id_card_back_place_holder_layout);
        mIdCardBackPlaceHolderLayout.setOnClickListener(this);

        mIdCardBackLayout=findViewById(R.id.id_card_back_layout);

        mSubmit=findViewById(R.id.submit);
        mSubmit.setOnClickListener(this);

        mProgressBar=findViewById(R.id.progressBar);

        mProgressBarLayout=findViewById(R.id.progressBar_layout);
        mContentView=findViewById(R.id.content_view);

        back=findViewById(R.id.back);
        back.setOnClickListener(this);


    }

    ImageView mIdCardFrontImage;
    LinearLayout mClearFrontImage;
    LinearLayout mIdCardFrontPlaceHolderLayout;
    FrameLayout mIdCardFrontLayout;
    ImageView mIdCardBackImage;
    LinearLayout mClearBackImage;
    LinearLayout mIdCardBackPlaceHolderLayout;
    FrameLayout mIdCardBackLayout;
    TextView mSubmit;
    ProgressBar mProgressBar;
    FrameLayout mProgressBarLayout;
    LinearLayout mContentView;

    View back;

    //上一步传过来的人脸照片Path、转base64用
    private String mPhotoPath;
    //身份证正面照path
    private String mFrontIdCardPath;
    //身份证背面照path
    private String mBackIdCardPath;
//    //身份证正面照bitmap、用来显示ui
//    private Bitmap mFrontIdCard;
//    //身份证反面照bitmap、用来显示ui
//    private Bitmap mBackIdCard;
    //当前点击证件照转为byte时的临时数据
    private String mIdCardTempBase64;
    //参数
    private String mIdCardName;
    private String mIdCardNum;
    private String mBase64Photo;
    private String mBase64IdCardFrontPhoto;
    private String mBase64IdCardBackPhoto;

    private long mClickTime;


    private File mFile;
    private Uri mUri;
    private String mCurrentType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.id_card_verify_step_two_layout);
        initFindView();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        mPhotoPath = intent.getStringExtra("PHOTO_PATH");
        getData(mPhotoPath);
        mIdCardName = intent.getStringExtra("ID_CARD_NAME");
        mIdCardNum = intent.getStringExtra("ID_CARD_NUM");

        mProgressBarLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
    }

    private void getBase64Photo(final String path) {
        if (TextUtils.isEmpty(path)) {
            Log.e(TAG, "getBase64Photo: ", new Throwable("path is null!"));
            hideLoading();
            return;
        }
        if (mHandler == null) {
            mHandler = new PhotoHandler(this);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                mIdCardTempBase64 = Base64Utils.photoToBase64(IDCardVerifyStepTwoActivity.this, path);
                if (TextUtils.isEmpty(mIdCardTempBase64)) {
                    mHandler.sendEmptyMessage(0);
                } else {
                    mHandler.sendEmptyMessage(1);
                }
            }
        }).start();
    }


    private void getData(String path) {
        if (TextUtils.isEmpty(path)){
            Toast.makeText(this,"人脸照片参数有误，请重新上传",Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        showLoading();
        getBase64Photo(path);
    }

    private void clearImage(String type){
        if ("front".equals(type)){
            mIdCardFrontImage.setImageDrawable(null);
            mClearFrontImage.setVisibility(View.GONE);
            mIdCardFrontPlaceHolderLayout.setVisibility(View.VISIBLE);
            mIdCardFrontImage.setVisibility(View.GONE);
        }else {
            mIdCardBackImage.setImageDrawable(null);
            mClearBackImage.setVisibility(View.GONE);
            mIdCardBackPlaceHolderLayout.setVisibility(View.VISIBLE);
            mIdCardBackImage.setVisibility(View.GONE);

        }
    }

    private void checkPermission(){

        int hasWritePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int hasTakePhotoPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA);
        if (hasWritePermission != PackageManager.PERMISSION_GRANTED && hasTakePhotoPermission != PackageManager.PERMISSION_GRANTED){
            PermissionGen.with(this)
                    .addRequestCode(REQUEST_CODE_REQUEST_PERMISSIONS)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                    .request();
        } else if (hasTakePhotoPermission != PackageManager.PERMISSION_GRANTED){
            PermissionGen.with(this)
                    .addRequestCode(REQUEST_CODE_REQUEST_PERMISSIONS)
                    .permissions(Manifest.permission.CAMERA)
                    .request();
        } else if (hasWritePermission != PackageManager.PERMISSION_GRANTED ){
            PermissionGen.with(this)
                    .addRequestCode(REQUEST_CODE_REQUEST_PERMISSIONS)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request();
        }else {
            takePhoto();
        }
    }

    private void takePhoto(){

        try {
            mFile = FileUtils.createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        Log.d(TAG, "takePhoto: "+mFile.getAbsolutePath());
        mUri =null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //Android 7.0及以上获取文件 Uri
            mUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()+".provider", mFile);
        } else {
            //获取文件Uri
            mUri = Uri.fromFile(mFile);
        }
        //调取系统拍照
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO_CODE);

    }


    private boolean verifyData(){

        if (TextUtils.isEmpty(mIdCardName)){
            Toast.makeText(this,"姓名不能为空",Toast.LENGTH_LONG).show();
            return false;
        }
        if (mIdCardName.length() > 8){
            Toast.makeText(this,"姓名长度不正确",Toast.LENGTH_LONG).show();
            return false;
        }

        if (TextUtils.isEmpty(mIdCardNum)){
            Toast.makeText(this,"身份证号不能为空",Toast.LENGTH_LONG).show();
            return false;
        }
        if (mIdCardNum.length() != 18){
            Toast.makeText(this,"身份证号格式错误，请重新输入",Toast.LENGTH_LONG).show();
            return false;
        }

        if (TextUtils.isEmpty(mBase64Photo)){
            Toast.makeText(this,"患者正面人脸照片有误，请重新上传",Toast.LENGTH_LONG).show();
            return false;
        }




        Log.d(TAG, "verifyData: "+MainActivity.ticket);
        Log.d(TAG, "verifyData: "+mIdCardName);
        Log.d(TAG, "verifyData: "+mIdCardNum);
        Log.d(TAG, "verifyData: "+mBase64Photo);
        Log.d(TAG, "verifyData: "+mBase64IdCardFrontPhoto);
        Log.d(TAG, "verifyData: "+mBase64IdCardBackPhoto);

        return  true;

    }

    private void submit(){
        if (verifyData()){
            Toast.makeText(this,"发送数据",Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_TAKE_PHOTO_CODE) {//获取系统照片上传
            Log.d(TAG, "onActivityResult:user photo is: "+mUri);
            String uriPath = mUri.getPath();
            if (TextUtils.isEmpty(uriPath)){
                Log.e(TAG, "onActivityResult: ",new Throwable("照片文件不存在！"));
                return;
            }
            showLoading();
            if ("front".equals(mCurrentType)){
                mFrontIdCardPath = Environment.getExternalStorageDirectory()+uriPath.split("external_files")[1];
                getBase64Photo(mFrontIdCardPath);

            }else {
                mBackIdCardPath = Environment.getExternalStorageDirectory()+uriPath.split("external_files")[1];
                getBase64Photo(mBackIdCardPath);

            }
        }
//        else if (resultCode == REQUEST_OK && requestCode == REQUEST_CODE_PREVIEW_WAITTING_SESSION){
//            postData();
//        }else if (resultCode == RESULT_CANCELED && requestCode == REQUEST_CODE_PREVIEW_WAITTING_SESSION){
//        }
    }

    private PhotoHandler mHandler;

/*
    @OnClick({R.id.back, R.id.id_card_front_image, R.id.clear_front_image, R.id.id_card_front_place_holder_layout, R.id.clear_back_image, R.id.id_card_back_place_holder_layout, R.id.submit})
    public void onViewClicked(View view) {


        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.id_card_front_image:
                break;
            case R.id.clear_front_image:
                clearImage("front");
                break;
            case R.id.id_card_front_place_holder_layout:
                mCurrentType = "front";
                checkPermission();
                break;
            case R.id.clear_back_image:
                clearImage("back");
                break;
            case R.id.id_card_back_place_holder_layout:
                mCurrentType = "back";
                checkPermission();
                break;
            case R.id.submit:
                if (System.currentTimeMillis() - mClickTime < 1000){//防止双击
                    return;
                }
                submit();
                mClickTime = System.currentTimeMillis();
                break;
        }
    }*/

    private void showLoading(){
        mProgressBarLayout.setVisibility(View.VISIBLE);
    }

    private void hideLoading(){
        mProgressBarLayout.setVisibility(View.GONE);
    }

//    @Override
    public void onSuccess() {
        if ("front".equals(mCurrentType)){
            Glide.with(this).load(mUri).into(mIdCardFrontImage);
            mClearFrontImage.setVisibility(View.VISIBLE);
            mIdCardFrontImage.setVisibility(View.VISIBLE);
            mIdCardFrontPlaceHolderLayout.setVisibility(View.GONE);
            mBase64IdCardFrontPhoto = mIdCardTempBase64;
        }else if ("back".equals(mCurrentType)){
            Glide.with(this).load(mUri).into(mIdCardBackImage);
            mClearBackImage.setVisibility(View.VISIBLE);
            mIdCardBackImage.setVisibility(View.VISIBLE);
            mIdCardBackPlaceHolderLayout.setVisibility(View.GONE);
            mBase64IdCardBackPhoto = mIdCardTempBase64;
        }else{
            mBase64Photo = mIdCardTempBase64;
        }
        hideLoading();
    }

//    @Override
    public void onFailure() {
        if ("front".equals(mCurrentType)){
            Toast.makeText(this,"解析转码身份证正面照失败！",Toast.LENGTH_LONG);
        }else {
            Toast.makeText(this,"解析转码身份证反面照失败！",Toast.LENGTH_LONG);
        }
        hideLoading();
    }



//    public interface PathToBase64CallBack{
//        void onSuccess();
//        void onFailure();
//    }

    public static class PhotoHandler extends Handler {
        private WeakReference<IDCardVerifyStepTwoActivity> weakReference;
//        private PathToBase64CallBack callBack;

        public PhotoHandler(IDCardVerifyStepTwoActivity activity) {
            this.weakReference = new WeakReference<IDCardVerifyStepTwoActivity>(activity);
//            this.callBack = activity;

        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            IDCardVerifyStepTwoActivity activity = weakReference.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        activity.onSuccess();
//                        ((IDCardVerifyStepTwoActivity) activity).updatePhoto();
                        break;
                    case 0:

                        activity.onFailure();
                        break;
                    default:

                }
            }
        }
    }
}
